<template>
  <div class="mini-house-page">
    <div class="mini-house-container">
      <h1>迷你屋</h1>
      
      <el-row :gutter="20">
        <el-col :span="16">
          <div class="canvas-container">
            <canvas ref="canvas" 
                   width="600" 
                   height="400" 
                   @mousedown="startDrag" 
                   @mousemove="drag" 
                   @mouseup="stopDrag" 
                   @wheel="zoom">
            </canvas>
          </div>
          <el-button type="primary" @click="addCustomGif" class="custom-btn">
            <el-icon><Upload /></el-icon>
            添加自定义GIF
          </el-button>
        </el-col>

        <el-col :span="8">
          <el-tabs>
            <el-tab-pane v-for="category in categories" 
                        :key="category" 
                        :label="category">
              <el-scrollbar height="300px">
                <div class="item-list">
                  <div v-for="(item, index) in getItemsByCategory(category)" 
                       :key="index" 
                       class="item-wrapper">
                    <img :src="item" 
                         class="item" 
                         @click="addItemToCanvas(item)">
                  </div>
                </div>
              </el-scrollbar>
            </el-tab-pane>
          </el-tabs>
        </el-col>
      </el-row>

      <div class="button-group">
        <el-button type="success" @click="saveCanvas">
          <el-icon><Download /></el-icon>
          保存作品
        </el-button>
        <el-button type="warning" @click="returnToHomepage">
          <el-icon><Back /></el-icon>
          返回首页
        </el-button>
      </div>

      <div class="notes">
        <h3>帮助说明：</h3>
        <ul>
          <li>点击右侧素材添加到画布</li>
          <li>可拖拽移动素材位置</li>
          <li>使用鼠标滚轮调整素材大小</li>
          <li>点击素材可选中并删除</li>
          <li>支持上传自定义GIF图片</li>
          <li>完成后可保存作品</li>
        </ul>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Upload, Download, Back } from '@element-plus/icons-vue'

const router = useRouter()
const canvas = ref(null)
const ctx = ref(null)
const canvasItems = ref([])
const isDragging = ref(false)
const draggedItemIndex = ref(-1)
const lastMousePos = ref({ x: 0, y: 0 })
const selectedItemIndex = ref(-1)
let animationFrameId = null

const categories = ref(['地板', '墙壁', '背景', '家具', '装饰'])
const items = ref({})

const loadDefaultItems = () => {
  categories.value.forEach(category => {
    items.value[category] = [
      '/images/qqhouse/0原始壁纸.gif',
      '/images/qqhouse/169655790482943.gif',
    ]
  })
}

const getItemsByCategory = (category) => {
  return items.value[category] || []
}

const addItemToCanvas = (itemSrc) => {
  const gifImg = document.createElement('img')
  gifImg.src = itemSrc
  gifImg.onload = () => {
    const item = {
      image: gifImg,
      x: Math.random() * (canvas.value.width - gifImg.width),
      y: Math.random() * (canvas.value.height - gifImg.height),
      width: gifImg.width,
      height: gifImg.height
    }
    canvasItems.value.push(item)
    drawCanvas()
  }
}

const drawCanvas = () => {
  if (!canvas.value || !ctx.value) return
  ctx.value.clearRect(0, 0, canvas.value.width, canvas.value.height)
  
  canvasItems.value.forEach((item, index) => {
    ctx.value.drawImage(item.image, item.x, item.y, item.width, item.height)
    
    if (index === selectedItemIndex.value) {
      ctx.value.strokeStyle = '#409EFF'
      ctx.value.lineWidth = 2
      ctx.value.strokeRect(item.x, item.y, item.width, item.height)
    }
  })
}

const startDrag = (event) => {
  const rect = canvas.value.getBoundingClientRect()
  const x = event.clientX - rect.left
  const y = event.clientY - rect.top

  for (let i = canvasItems.value.length - 1; i >= 0; i--) {
    const item = canvasItems.value[i]
    if (x >= item.x && x <= item.x + item.width &&
        y >= item.y && y <= item.y + item.height) {
      isDragging.value = true
      draggedItemIndex.value = i
      selectedItemIndex.value = i
      lastMousePos.value = { x, y }
      break
    }
  }
}

const drag = (event) => {
  if (!isDragging.value) return
  
  const rect = canvas.value.getBoundingClientRect()
  const x = event.clientX - rect.left
  const y = event.clientY - rect.top
  
  const dx = x - lastMousePos.value.x
  const dy = y - lastMousePos.value.y
  
  const item = canvasItems.value[draggedItemIndex.value]
  if (item) {
    item.x += dx
    item.y += dy
  }
  
  lastMousePos.value = { x, y }
  drawCanvas()
}

const stopDrag = () => {
  isDragging.value = false
  draggedItemIndex.value = -1
}

const zoom = (event) => {
  if (selectedItemIndex.value === -1) return
  
  event.preventDefault()
  const item = canvasItems.value[selectedItemIndex.value]
  const scaleFactor = event.deltaY > 0 ? 0.9 : 1.1
  
  item.width *= scaleFactor
  item.height *= scaleFactor
  drawCanvas()
}

const addCustomGif = () => {
  const input = document.createElement('input')
  input.type = 'file'
  input.accept = 'image/gif'
  input.onchange = (e) => {
    const file = e.target.files[0]
    if (file) {
      const reader = new FileReader()
      reader.onload = (event) => {
        addItemToCanvas(event.target.result)
      }
      reader.readAsDataURL(file)
    }
  }
  input.click()
}

const saveCanvas = () => {
  const dataUrl = canvas.value.toDataURL('image/png')
  const link = document.createElement('a')
  link.download = '迷你屋作品.png'
  link.href = dataUrl
  link.click()
  ElMessage.success('作品已保存')
}

const returnToHomepage = () => {
  router.push('/')
}

onMounted(() => {
  canvas.value = document.querySelector('canvas')
  ctx.value = canvas.value.getContext('2d')
  loadDefaultItems()
  
  window.addEventListener('keydown', (e) => {
    if (e.key === 'Delete' && selectedItemIndex.value !== -1) {
      canvasItems.value.splice(selectedItemIndex.value, 1)
      selectedItemIndex.value = -1
      drawCanvas()
    }
  })
})

onUnmounted(() => {
  if (animationFrameId) {
    cancelAnimationFrame(animationFrameId)
  }
})
</script>

<style lang="scss" scoped>
.mini-house-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
  box-sizing: border-box;

  .mini-house-container {
    max-width: 1200px;
    margin: 0 auto;
    background-color: rgba(255, 255, 255, 0.95);
    border-radius: 20px;
    padding: 30px;
    box-shadow: 0 15px 30px rgba(0, 0, 0, 0.2);

    h1 {
      text-align: center;
      color: #4a5568;
      font-size: 28px;
      margin-bottom: 30px;
      text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.1);
    }

    .canvas-container {
      border: 2px solid #dcdfe6;
      border-radius: 8px;
      overflow: hidden;
      margin-bottom: 20px;

      canvas {
        background-color: #f5f7fa;
        width: 100%;
        height: 400px;
        cursor: move;
      }
    }

    .item-list {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(80px, 1fr));
      gap: 10px;
      padding: 10px;

      .item-wrapper {
        aspect-ratio: 1;
        border-radius: 4px;
        overflow: hidden;
        border: 1px solid #dcdfe6;
        transition: all 0.3s ease;

        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
        }

        .item {
          width: 100%;
          height: 100%;
          object-fit: cover;
          cursor: pointer;
        }
      }
    }

    .custom-btn {
      width: 100%;
      margin-bottom: 20px;
    }

    .button-group {
      display: flex;
      gap: 15px;
      margin-top: 30px;
      justify-content: center;

      .el-button {
        min-width: 120px;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 8px;
      }
    }

    .notes {
      margin-top: 40px;
      padding: 20px;
      background-color: #f0f5ff;
      border-radius: 12px;
      text-align: left;

      h3 {
        color: #409EFF;
        margin: 0 0 15px 0;
        font-size: 16px;
      }

      ul {
        margin: 0;
        padding-left: 20px;
        
        li {
          margin-bottom: 8px;
          color: #606266;
          line-height: 1.6;

          &:last-child {
            margin-bottom: 0;
          }
        }
      }
    }
  }
}

@media (max-width: 768px) {
  .mini-house-page {
    padding: 10px;

    .mini-house-container {
      padding: 20px;

      h1 {
        font-size: 24px;
        margin-bottom: 20px;
      }

      .button-group {
        flex-direction: column;

        .el-button {
          width: 100%;
        }
      }
    }
  }
}
</style>
